package net.forsalemall.android;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.forsalemall.android.AdsByMeActivity.ListItem;

import org.json.JSONArray;
import org.json.JSONObject;
import org.taptwo.android.widget.TitleProvider;

import com.github.droidfu.widgets.ImageLoadListener;
import com.github.droidfu.widgets.WebImageView;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.ImageUtils;
import com.utils.Utils;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AdDetailsActivity extends ListActivity {

	private static final String[] ALLOWED_URLS = { "http://www.youtube.com/",
			"http://youtube.com/", "http://m.youtube.com/",
			"https://youtube.com/", "https://www.youtube.com/",
			"https://m.youtube.com/" ,"http://youtu.be/" };

	private List<String> fileNames;
	private String adData;
	private JSONObject jAd;
	private int adId;
	private String adDesc;
	private String phoneNo;
	private int viewCount;
	private int imgCount;
	private long time;
	private boolean isFromMyAd;
	private boolean isSold;

	private TextView descView;
	private TextView viewCountView;
	private TextView dateView;
	// private Button favButton;
	private ActionBar actionBar;
	private Action favAction;
	private boolean isFavorite;

	// private ViewFlow viewFlow;
	private ViewFlowAdapter viewFlowAdapter;

	private LayoutInflater mInflater;

	private View topView;
	private int windowWidth;

	private ImageLoadListener imageLoadListener = new ImageLoadListener() {

		public void imageLoaded(WebImageView webImageView, Bitmap bitmap) {
			if (bitmap != null && topView != null) {
				int height = (bitmap.getHeight() * topView.getWidth())
						/ bitmap.getWidth();
				webImageView.getLayoutParams().width = topView.getWidth();
				webImageView.getLayoutParams().height = height;
			}
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.ad_details);
			windowWidth = getWindowManager().getDefaultDisplay().getWidth();
			isFromMyAd = getIntent().getBooleanExtra(
					Constants.KEY_IS_FROM_MY_APP, false);
			isSold = getIntent().getBooleanExtra(Constants.KEY_IS_SOLD, false);
			mInflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			topView = mInflater.inflate(R.layout.ad_details_list_content_top,
					null);
			descView = (TextView) topView.findViewById(R.id.desc_view);
			viewCountView = (TextView) topView
					.findViewById(R.id.view_count_view);

			dateView = (TextView) topView.findViewById(R.id.time_view);

			actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getString(R.string.title_ads_details));
			fileNames = new ArrayList<String>();
			adId = getIntent().getIntExtra(Constants.KEY_AD_ID, -1);
			adDesc = getIntent().getStringExtra(Constants.KEY_AD_TEXT);
			isFavorite = false;
			actionBar.setHomeAction(new Action() {
				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});

			if (!isSold) {
				if (isFromMyAd) {
					actionBar.addAction(new Action() {
						public void performAction(View view) {
							editAd();
						}

						public int getDrawable() {
							return R.drawable.ic_menu_edit;
						}
					});
				} else {
					actionBar.addAction(new Action() {
						public void performAction(View view) {
							try {
								Intent intent = null;
								if (phoneNo != null) {
									intent = new Intent(Intent.ACTION_DIAL, Uri
											.parse("tel:" + phoneNo));
								} else {
									intent = new Intent(Intent.ACTION_DIAL);
								}
								startActivity(intent);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						public int getDrawable() {
							return R.drawable.ic_menu_call;
						}
					});
					actionBar.addAction(new Action() {
						public void performAction(View view) {
							try {
								Intent intent = null;
								if (phoneNo != null) {
									intent = new Intent(Intent.ACTION_SENDTO,
											Uri.parse("smsto:" + phoneNo));
								} else {
									intent = new Intent(Intent.ACTION_SENDTO);
								}
								startActivity(intent);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						public int getDrawable() {
							return R.drawable.ic_menu_send;
						}
					});
					favAction = new Action() {
						public void performAction(View view) {
							try {
								addRemoveFavorite();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						public int getDrawable() {
							return isFavorite ? R.drawable.ic_menu_unfavorite
									: R.drawable.ic_menu_favorite;
						}
					};
					actionBar.addAction(favAction);
				}
			}
			actionBar.setDisplayHomeAsUpEnabled(true);
			String desc = adDesc;

			List<String> urls = Utils.getLRLS(desc);
			for (int i = 0; i < urls.size(); i++) {
				String url = urls.get(i);

				for (int j = 0; j < ALLOWED_URLS.length; j++) {
					if (url.startsWith(ALLOWED_URLS[j])) {
						Log.i("DREG", url+"="+ALLOWED_URLS[j]);
						desc = desc.replace(url, "<u>" + url + "</u>");
						break;
					}else{
						Log.i("DREG", url+"!="+ALLOWED_URLS[j]);
					}
				}

			}
			Spanned text = Html.fromHtml(desc);
			final SpannableStringBuilder strBuilder = new SpannableStringBuilder(
					text);
			UnderlineSpan[] underlines = strBuilder.getSpans(0, text.length(),
					UnderlineSpan.class);
			for (final UnderlineSpan span : underlines) {
				final int start = strBuilder.getSpanStart(span);
				final int end = strBuilder.getSpanEnd(span);
				int flags = strBuilder.getSpanFlags(span);
				ClickableSpan myActivityLauncher = new ClickableSpan() {
					public void onClick(View view) {
						try {
							String url = strBuilder.subSequence(start, end)
									.toString();
							startActivity(new Intent(Intent.ACTION_VIEW,
									Uri.parse(url)));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};

				strBuilder.setSpan(myActivityLauncher, start, end, flags);
			}

			descView.setText(strBuilder);
			descView.setMovementMethod(LinkMovementMethod.getInstance());

			// descView.setText(adDesc);
			loadData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadData() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							AdDetailsActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					fileNames.clear();

					fileNames.add("");

					adData = HttpUtils.getAdDetails(adId,
							Utils.getDeviceId(AdDetailsActivity.this));
					jAd = new JSONObject(adData);
					if (jAd != null) {
						viewCount = jAd.getInt("view_count");
						imgCount = jAd.getInt("img_count");
						phoneNo = jAd.getString("pn");
						time = System.currentTimeMillis()
								- (jAd.getLong("time_diff") * 1000);
						isFavorite = (jAd.getInt("is_favorite") != 0);
						JSONArray ja = jAd.getJSONArray("img_file_names");
						for (int i = 0; i < ja.length(); i++) {
							fileNames.add(ja.getString(i));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					dateView.setText(Constants.SIMPLE_DATE_FORMAT
							.format(new Date(time)));

					viewCountView.setText(String.format(
							getString(R.string.view_count),
							Integer.toString(viewCount)));

					if (!isSold) {
						actionBar.setTitle(phoneNo);
						if (!isFromMyAd) {
							actionBar.removeAction(favAction);
							actionBar.addAction(favAction);
						}
					}

					if (fileNames.size() > 0) {
						viewFlowAdapter = new ViewFlowAdapter(fileNames);
						setListAdapter(viewFlowAdapter);
					}
					progressDialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void addRemoveFavorite() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							AdDetailsActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					if (isFavorite) {
						HttpUtils.removeFromFavorite(
								Utils.getDeviceId(AdDetailsActivity.this),
								Integer.toString(adId));
						isFavorite = false;
					} else {
						HttpUtils.addToFavorite(
								Utils.getDeviceId(AdDetailsActivity.this),
								Integer.toString(adId));
						isFavorite = true;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					// favButton
					// .setText(isFavorite ? R.string.remove_from_favorite
					// : R.string.add_to_favorite);
					actionBar.removeAction(favAction);
					actionBar.addAction(favAction);
					progressDialog.dismiss();
					Utils.showAlertMessage(AdDetailsActivity.this, null,
							isFavorite ? getString(R.string.favorited_ad)
									: getString(R.string.unfavorited_ad));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void editAd() {
		try {
			String[] fNames = new String[fileNames.size() - 1];
			for (int i = 1; i < fileNames.size(); i++) {
				fNames[i - 1] = fileNames.get(i);
			}
			Intent intent = new Intent(this, EditAdActivity.class);
			intent.putExtra(Constants.KEY_COUNTRY_CODE, getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE));
			intent.putExtra(Constants.KEY_AD_ID, adId);
			intent.putExtra(Constants.KEY_AD_TEXT, adDesc);
			intent.putExtra(Constants.KEY_PHONE_NO, phoneNo);
			intent.putExtra(Constants.KEY_CAT_INFO,
					getIntent().getStringExtra(Constants.KEY_CAT_INFO));
			intent.putExtra(Constants.KEY_FILE_NAMES, fNames);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class ViewFlowAdapter extends BaseAdapter implements TitleProvider {

		private List<String> items;
		private SparseArray<Bitmap> bitmaps;

		public ViewFlowAdapter(List<String> items) {
			this.items = items;
			this.bitmaps = new SparseArray<Bitmap>();

		}

		public int getCount() {
			return (items == null) ? 0 : items.size();
		}

		public Object getItem(int arg0) {
			Object ret = null;
			if (items != null && items.size() > arg0) {
				ret = items.get(arg0);
			}
			return ret;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == 0) {
				convertView = topView;
			} else {

				convertView = mInflater.inflate(
						R.layout.ad_details_list_content, null);
				ImageView imView = (ImageView) convertView
						.findViewById(R.id.list_image);
				ProgressBar pBar = (ProgressBar) convertView
						.findViewById(R.id.list_progressbar);
				Bitmap bm = bitmaps.get(position);
				if (bm != null) {
					pBar.setVisibility(View.INVISIBLE);
					imView.setVisibility(View.VISIBLE);
					imView.setImageBitmap(bm);
				} else {
					loadImage(bitmaps, HttpUtils.getFileUrl(
							Constants.getAdImgDirName(), items.get(position)),
							position, pBar, imView, windowWidth);
				}
				// wiv.setImageLoadListener(imageLoadListener);
				// wiv.setImageUrl(HttpUtils.getFileUrl(
				// Constants.getAdImgDirName(), items.get(position)));
				// wiv.loadImage();
			}
			return convertView;
		}

		class ViewHolder {
			WebImageView wiv;
		}

		public String getTitle(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}
	}

	private void loadImage(final SparseArray<Bitmap> sa, final String url,
			final int key, final ProgressBar progressBar,
			final ImageView imView, final int windowWidth) {
		try {

			new AsyncTask<String, String, String>() {
				protected void onPreExecute() {
					try {
						progressBar.setVisibility(View.VISIBLE);
						imView.setVisibility(View.INVISIBLE);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						byte[] bytes = HttpUtils.getHttpResponse(url);
						Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
								bytes.length);
						sa.put(key, ImageUtils.getResizeImage(bitmap,
								windowWidth, bitmap.getHeight() * windowWidth
										/ bitmap.getWidth()));
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						progressBar.setVisibility(View.INVISIBLE);
						imView.setVisibility(View.VISIBLE);
						imView.setImageBitmap(sa.get(key));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
